// /static/js/freecell.js

function safeGetColumn(event) {
    let column = event.target.closest('.tableau-column');
    if (!column) {
        return [null, null];
    }
    let columnIndex;
    try {
        columnIndex = parseInt(column.dataset.columnIndex);
    } catch (_) {
        columnIndex = null;
    }
    if (isNaN(columnIndex)) {
        return [null, null];
    }
    return [column, columnIndex];
}

function safeGetCell(event) {
    let cell = event.target.closest('.cell');
    if (!cell) {
        return [null, null];
    }
    let cellIndex;
    try {
        cellIndex = parseInt(cell.dataset.cellIndex);
    } catch (_) {
        cellIndex = null;
    }
    if (isNaN(cellIndex)) {
        return [null, null];
    }
    return [cell, cellIndex];
}

function findSource(event) {
    const [column, columnIndex] = safeGetColumn(event);
    if (column) {
        const topCard = column.querySelector('.card:last-child');
        return [columnIndex, topCard];
    }
    const [cell, cellIndex] = safeGetCell(event);
    if (cell) {
        const card = cell.querySelector('.card');
        return [-1 - cellIndex, card];
    }
    return [null, null];
}

function findTarget(event) {
    const [, columnIndex] = safeGetColumn(event);
    if (columnIndex !== null)
        return columnIndex;

    const [cell, cellIndex] = safeGetCell(event);
    if (cellIndex !== null && cell) {
        const card = cell.querySelector('.card');
        return card ? null : -1 - cellIndex;
    }

    const foundation = event.target.closest('.piles');
    if (foundation) {
        return -5;
    }
    return null;
}

function handleClick(event) {
    event.stopPropagation(); // Prevent click from bubbling to document

    if (!selectedCard) {
        [sourceItem, selectedCard] = findSource(event);
        if (selectedCard) {
            showArrow(selectedCard);
        }
    } else {
        const srcItem = sourceItem; // backup before destroying
        resetToWaiting();
        if (srcItem === null) return;
        const targetItem = findTarget(event);
        if (targetItem === null) return;
        if (srcItem >= 0) {
            if (targetItem >= 0) {
                if (targetItem == srcItem) return;
                window.location.href = `/game_update/tt${srcItem}${targetItem}`;
            } else if (targetItem == -5) {
                window.location.href = `/game_update/tf${srcItem}`;
            } else {
                window.location.href = `/game_update/tc${srcItem}${-1 - targetItem}`;
            }
        } else {
            if (targetItem >= 0) {
                window.location.href = `/game_update/ct${-1 - srcItem}${targetItem}`;
            } else if (targetItem == -5) {
                window.location.href = `/game_update/cf${-1 - srcItem}`;
            }
        }
    }
}

function handleDoubleClick(event) {
    event.stopPropagation(); // Prevent double-click from bubbling

    resetToWaiting();
    const [dblSourceItem,] = findSource(event);
    if (dblSourceItem === null) return;

    if (dblSourceItem >= 0) {
        window.location.href = `/game_update/tf${dblSourceItem}`;
    } else {
        window.location.href = `/game_update/cf${-1 - dblSourceItem}`;
    }
}

function resetToWaiting() {
    sourceItem = null;
    selectedCard = null;
    arrow.style.display = 'none';
}

function showArrow(card) {
    // Get the bounding box of the last card
    const rect = card.getBoundingClientRect();

    // Position arrow centered on the last card
    const arrowWidth = 2 * window.innerWidth / 100; // 2vw
    const arrowHeight = arrowWidth * (rect.height / rect.width); // Approximate height based on card aspect ratio
    const left = rect.left + (rect.width / 2); // Center of the card
    const top = rect.top + (rect.height / 2) - (arrowHeight / 2); // Center vertically on the card

    arrow.style.left = `${left}px`;
    arrow.style.top = `${top}px`;
    arrow.style.display = 'block';
}

let sourceItem = null; // selected item can be a column or a cell
let selectedCard = null;
const arrow = document.querySelector('.highlight-arrow');
const gameArea = document.querySelector('.game-area');
gameArea.addEventListener('click', handleClick);
gameArea.addEventListener('dblclick', handleDoubleClick);